package com.example.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.ruiji.common.Result;
import com.example.ruiji.entity.ShoppingCart;
import com.example.ruiji.mapper.ShoppingCartMapper;
import com.example.ruiji.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    HttpSession httpSession;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Override
    public Result<ShoppingCart> add(ShoppingCart shoppingCart) {
        Long userId = (Long) httpSession.getAttribute("userId");
        shoppingCart.setUserId(userId);

        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);

        Long dishId = shoppingCart.getDishId();
        if (!Objects.isNull(dishId)) {
            lambdaQueryWrapper.eq(ShoppingCart::getDishId, dishId);
        }
        else  {
            lambdaQueryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart shoppingCart1 = shoppingCartMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(shoppingCart1)) {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        }
        else {
            shoppingCart1.setNumber(shoppingCart1.getNumber() + 1);
            shoppingCartMapper.updateById(shoppingCart1);
        }
        return Result.success(shoppingCart1);
    }

    @Override
    public Result<List<ShoppingCart>> list() {
        Long userId = (Long) httpSession.getAttribute("userId");
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        lambdaQueryWrapper.orderByDesc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(lambdaQueryWrapper);
        return Result.success(shoppingCarts);
    }

    @Override
    public Result<String> clean() {
        Long userId = (Long) httpSession.getAttribute("userId");
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        shoppingCartMapper.delete(lambdaQueryWrapper);
        return Result.success("清空成功");
    }
}
